#!/usr/bin/env node
/**
 * Phase4 基于Gap的面板评估脚本
 *
 * 目的: 基于Phase3.5的gap report,决策是否需要生成自定义面板
 * 改进: 不再基于配置假设,而是基于文件系统扫描事实
 *
 * 执行时机: Phase3.5完成后
 * 质量门控: gap.missingPanels.length === 0 才能跳过Phase4
 */

const fs = require('fs');
const path = require('path');

const PROJECT_ROOT = path.resolve(__dirname, '..');

/**
 * 扫描实际存在的自定义面板文件
 */
function scanExistingCustomPanels(componentCode) {
  const rightDir = path.join(PROJECT_ROOT, 'src/components/editor/Right');
  const panelDirs = [
    'renderBasicInfo',
    'renderCardStyle',
    'renderTitleStyle',
    'renderComponentStyle',
    'renderStaticTexStyle',
    'renderDashboardThemeType',
    'renderDashboardThemeTypeMuti'
  ];

  const existingPanels = [];

  for (const dir of panelDirs) {
    const panelDir = path.join(rightDir, dir);

    if (!fs.existsSync(panelDir)) continue;

    const componentPanelFile = path.join(panelDir, `render${componentCode}.tsx`);

    if (fs.existsSync(componentPanelFile)) {
      const stats = fs.statSync(componentPanelFile);

      existingPanels.push({
        panelType: dir,
        filePath: componentPanelFile,
        relativePath: path.relative(PROJECT_ROOT, componentPanelFile),
        lastModified: stats.mtime.toISOString(),
        size: stats.size
      });
    }
  }

  return existingPanels;
}

/**
 * 读取Figma auxiliary面板结构
 */
function readFigmaAuxiliaryStructure(componentCode) {
  const phase1Dir = path.join(PROJECT_ROOT, `${componentCode}/phase1`);

  const auxiliaryData = {
    available: false,
    content: null,
    style: null,
    totalSections: 0
  };

  const contentPath = path.join(phase1Dir, 'auxiliary/content/panel-structure.json');
  const stylePath = path.join(phase1Dir, 'auxiliary/style/panel-structure.json');

  if (fs.existsSync(contentPath)) {
    auxiliaryData.content = JSON.parse(fs.readFileSync(contentPath, 'utf-8'));
    auxiliaryData.totalSections += (auxiliaryData.content.sections || []).length;
    auxiliaryData.available = true;
  }

  if (fs.existsSync(stylePath)) {
    auxiliaryData.style = JSON.parse(fs.readFileSync(stylePath, 'utf-8'));
    auxiliaryData.totalSections += (auxiliaryData.style.sections || []).length;
    auxiliaryData.available = true;
  }

  return auxiliaryData;
}

/**
 * 对比面板结构:实际文件 vs Figma设计
 */
function comparePanelStructures(existingPanels, figmaAuxiliary, gapReport) {
  const comparison = {
    matched: [],
    missing: [],
    extra: [],
    score: 0
  };

  // 1. 从gap report获取缺失面板
  if (gapReport?.gap?.missingPanels) {
    comparison.missing = gapReport.gap.missingPanels.map(p => ({
      expectedPath: p.expectedPath,
      reference: p.reference,
      source: 'gap_report'
    }));
  }

  // 2. 对比Figma auxiliary
  if (figmaAuxiliary.available) {
    const figmaSections = [];

    if (figmaAuxiliary.content) {
      figmaSections.push(...(figmaAuxiliary.content.sections || []).map(s => ({
        ...s,
        panelType: 'content',
        nodeId: figmaAuxiliary.content.nodeId
      })));
    }

    if (figmaAuxiliary.style) {
      figmaSections.push(...(figmaAuxiliary.style.sections || []).map(s => ({
        ...s,
        panelType: 'style',
        nodeId: figmaAuxiliary.style.nodeId
      })));
    }

    // 检查每个Figma section是否有对应实现
    for (const section of figmaSections) {
      const hasImplementation = existingPanels.some(p => {
        // 简化匹配:检查文件是否存在
        return true; // 这里需要更精细的匹配逻辑
      });

      if (!hasImplementation && !comparison.missing.some(m => m.nodeId === section.nodeId)) {
        comparison.missing.push({
          sectionTitle: section.title || section.name,
          nodeId: section.nodeId,
          panelType: section.panelType,
          fields: section.fields || [],
          source: 'figma_auxiliary'
        });
      }
    }
  }

  // 3. 计算匹配度
  const totalExpected = existingPanels.length + comparison.missing.length;
  comparison.score = totalExpected > 0 ? existingPanels.length / totalExpected : 1;

  return comparison;
}

/**
 * 生成自定义面板spec
 */
function generateCustomPanelSpec(missingPanels, figmaAuxiliary, componentCode) {
  const spec = {
    componentCode,
    panels: [],
    totalFields: 0
  };

  for (const missing of missingPanels) {
    let panel;

    if (missing.source === 'gap_report') {
      // 基于gap report的缺失面板
      panel = {
        belongTo: missing.reference.panelName || missing.reference.slotName,
        path: missing.expectedPath,
        purpose: `${missing.reference.type} 引用的自定义面板`,
        fields: [], // 需要从Edit配置提取
        complexity: 'medium',
        variantSpecific: null
      };
    } else if (missing.source === 'figma_auxiliary') {
      // 基于Figma auxiliary的缺失面板
      panel = {
        belongTo: inferBelongToFromSection(missing.sectionTitle, missing.panelType),
        figmaNodeId: missing.nodeId,
        purpose: `${missing.sectionTitle} - ${missing.panelType}面板`,
        fields: missing.fields.map(f => f.fieldKey || f.label),
        complexity: missing.fields.length > 5 ? 'high' : 'low',
        variantSpecific: null // 需要检测variant信息
      };

      spec.totalFields += missing.fields.length;
    }

    if (panel) {
      spec.panels.push(panel);
    }
  }

  return spec;
}

/**
 * 从section名称推断belongTo
 */
function inferBelongToFromSection(sectionTitle, panelType) {
  const titleLower = sectionTitle.toLowerCase();

  if (titleLower.includes('title')) return 'renderTitleStyle';
  if (titleLower.includes('card') || titleLower.includes('background')) return 'renderCardStyle';
  if (titleLower.includes('component')) return 'renderComponentStyle';
  if (titleLower.includes('basic') || titleLower.includes('info')) return 'renderBasicInfo';
  if (titleLower.includes('theme')) return 'renderDashboardThemeType';

  // 默认根据panelType
  return panelType === 'content' ? 'renderBasicInfo' : 'renderComponentStyle';
}

/**
 * 主评估函数
 */
async function evaluateCustomPanels(componentCode) {
  console.log(`\n=== Phase4 Gap-Based Evaluation: ${componentCode} ===\n`);

  const evaluation = {
    timestamp: new Date().toISOString(),
    componentCode,
    filesystemScan: {},
    figmaStructure: {},
    comparison: {},
    decision: {}
  };

  // Step 1: 读取Phase3.5 gap report
  console.log('Step 1: 读取Phase3.5验证报告...');
  const gapReportPath = path.join(
    PROJECT_ROOT,
    `${componentCode}/phase3.5/implementation-verification-report.json`
  );

  let gapReport = null;

  if (fs.existsSync(gapReportPath)) {
    gapReport = JSON.parse(fs.readFileSync(gapReportPath, 'utf-8'));
    console.log(`✅ 发现gap report,缺失面板: ${gapReport.gap.missingPanels.length}`);
  } else {
    console.log('⚠️  未找到Phase3.5报告,将基于文件扫描评估');
  }

  // Step 2: 扫描实际存在的面板文件
  console.log('\nStep 2: 扫描文件系统中的自定义面板...');
  const existingPanels = scanExistingCustomPanels(componentCode);
  console.log(`发现 ${existingPanels.length} 个已实现的自定义面板:`);

  existingPanels.forEach(p => {
    console.log(`  ✅ ${p.relativePath}`);
  });

  evaluation.filesystemScan = {
    existingPanels,
    count: existingPanels.length
  };

  // Step 3: 读取Figma auxiliary结构
  console.log('\nStep 3: 读取Figma auxiliary面板结构...');
  const figmaAuxiliary = readFigmaAuxiliaryStructure(componentCode);

  if (figmaAuxiliary.available) {
    console.log(`✅ 发现 ${figmaAuxiliary.totalSections} 个Figma auxiliary sections`);
  } else {
    console.log('⚠️  无Figma auxiliary数据');
  }

  evaluation.figmaStructure = figmaAuxiliary;

  // Step 4: 对比结构计算gap
  console.log('\nStep 4: 对比实际实现与设计...');
  const comparison = comparePanelStructures(existingPanels, figmaAuxiliary, gapReport);

  console.log(`匹配度: ${(comparison.score * 100).toFixed(1)}%`);
  console.log(`缺失面板: ${comparison.missing.length}`);

  evaluation.comparison = comparison;

  // Step 5: 决策
  console.log('\n=== 决策结果 ===\n');

  if (comparison.missing.length > 0) {
    console.log(`❌ 需要生成 ${comparison.missing.length} 个自定义面板`);

    const spec = generateCustomPanelSpec(comparison.missing, figmaAuxiliary, componentCode);

    evaluation.decision = {
      needsCustomPanels: true,
      action: 'generate',
      missingCount: comparison.missing.length,
      spec
    };

    // 保存spec
    const specPath = path.join(PROJECT_ROOT, `${componentCode}/phase4/custom-panel-spec.json`);
    const specDir = path.dirname(specPath);

    if (!fs.existsSync(specDir)) {
      fs.mkdirSync(specDir, { recursive: true });
    }

    fs.writeFileSync(specPath, JSON.stringify(spec, null, 2), 'utf-8');
    console.log(`\nPanel spec已保存: ${path.relative(PROJECT_ROOT, specPath)}`);
  } else {
    console.log('✅ 所有面板已实现,无需生成');

    evaluation.decision = {
      needsCustomPanels: false,
      action: 'skip_phase4',
      reason: '文件系统扫描显示所有引用的面板已存在'
    };
  }

  // 保存评估报告
  const outputPath = path.join(PROJECT_ROOT, `${componentCode}/phase4/gap-based-evaluation.json`);
  const outputDir = path.dirname(outputPath);

  if (!fs.existsSync(outputDir)) {
    fs.mkdirSync(outputDir, { recursive: true });
  }

  fs.writeFileSync(outputPath, JSON.stringify(evaluation, null, 2), 'utf-8');
  console.log(`\n评估报告已保存: ${path.relative(PROJECT_ROOT, outputPath)}`);

  return evaluation;
}

// CLI执行
if (require.main === module) {
  const componentCode = process.argv[2];

  if (!componentCode) {
    console.error('用法: node scripts/phase4-gap-based-evaluation.js <ComponentCode>');
    process.exit(1);
  }

  evaluateCustomPanels(componentCode)
    .then(evaluation => {
      process.exit(0);
    })
    .catch(err => {
      console.error('执行失败:', err);
      process.exit(1);
    });
}

module.exports = { evaluateCustomPanels };
